use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Instant;
use log::info;

#[test]
fn any_test() {
    let h = "hello world".to_string();
    let str : Box<String> = Box::new(h);
    let any : &dyn Any = &*str;

    if let Some(value) = any.downcast_ref::<String>() {
        info!("value : {}", value);
    } else {
        info!("value is null");
    }
}

#[test]
fn map_any_test() {
    let mut map : HashMap<String, Box<dyn Any>> = HashMap::new();
    map.insert("hello".to_string(), Box::new("world".to_string()));

    {
        let value = map.get("hello").unwrap();
        if let Some(value) = value.downcast_ref::<String>() {
            info!("value : {}", value);
        } else {
            info!("value is null");
        }
    }


    map.insert("t2".to_string(), Box::new(12));

    {
        let value2 = map.get("t2").unwrap();
        if let Some(value) = value2.downcast_ref::<i32>() {
            info!("value2 : {}", value);
        } else {
            info!("value2 is null");
        }
    }

}

#[test]
fn map_arc_any_test() {
    let mut map : Arc<RwLock<HashMap<String, Box<dyn Any>>>> = Arc::new(RwLock::new(HashMap::new()));
    let k = "hello".to_string();
    map.write().unwrap().insert(k.clone(), Box::new("world".to_string()));

    {
        let lock = map.read().unwrap();
        let value = lock.get("hello");
        if let Some(value) = value {
            if let Some(value) = value.downcast_ref::<String>() {
                info!("value : {}", value);
            } else {
                info!("value is null");
            }
        }
    }


    let key = "example".to_string();
    let value: Box<dyn Any> = Box::new(42_i32);
    map.write().unwrap().insert(key.clone(), value);

    {
        let read_map = map.read().unwrap(); // 获取读锁
        if let Some(boxed_value) = read_map.get(&key) {
            // 尝试将 Box<dyn Any> 向下转换为 &i32
            if let Some(value) = boxed_value.downcast_ref::<i32>() {
                info!("找到 i32 值: {}", value);
            } else {
                info!("类型不匹配或不是 i32");
            }
        } else {
            info!("键不存在");
        }
    }

}

struct SessionDataItem {
    data: Box<dyn Any>,
    expired_time: Instant, // 过期时间， 默认100年后过期
}